package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.List;

public class AutoTestUtil {
    public static WebDriver driver;
    public static WebDriverWait wait;
    public static void createDriver(){
        WebDriverManager.chromedriver().setup();
        ChromeOptions options=new ChromeOptions();
//        强制运行所有的链接
        options.addArguments("--remote-allow-origins=*");
//        options.addArguments("--headless");

        driver=new ChromeDriver(options);
    }

    public AutoTestUtil(String url){
        createDriver();
        driver.get(url);
        wait=new WebDriverWait(driver, Duration.ofSeconds(2));
    }

    public void getScreenShot(String name) throws IOException {
        SimpleDateFormat sim1=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2=new SimpleDateFormat("hhMMssSS");

        String dirTime=sim1.format(System.currentTimeMillis());
        String fileTime=sim2.format(System.currentTimeMillis());

//        ./src/test/image/2025-03-15/name-fileTime.png
        String fileName=new String("./src/test/image/"+dirTime+"/"+name+"-"+fileTime+".png");

        File file=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(file,new File(fileName));
    }
    public void getToastContent(){
        wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("body > div.jq-toast-wrap.bottom-right > div"))));
        List<WebElement> toastElements=driver.findElements(By.cssSelector("body > div.jq-toast-wrap.bottom-right > div"));
        WebElement latestToast=toastElements.get(toastElements.size() - 1);
        System.out.println("弹窗内容："+latestToast.getText());
    }
}
